$(document).ready(function(){
    getLastPaidMoney();
    checkIsPhone();
    var userAgenta = navigator.userAgent;
    var isMinia = /miniProgram/i.test(userAgenta);
    if(isMinia || (isWeChat() && !isPCWeChat())){
        paymentChange(1);
        $("#payment_2").hide();
    }
});
function productChange(product_id) {
    $("#product_lists li").removeClass("active");
    $("#product_id"+product_id).addClass("active");
    $("#product_id").val(product_id);
    getLastPaidMoney();
}

function checkIsPhone() {
    var info = navigator.userAgent;
    var isPhone = /mobile/i.test(info);
    if (isPhone) {
        $("#device").val("phone");
    } else {
        $("#device").val("pc");
    }
}

function monthChange(month) {
    $("#month").val(month);
    $("#month_lists li").removeClass("active");
    $("#month_"+month).addClass("active");
    getLastPaidMoney();
}

function getLastPaidMoney() {
    var product_id = $("#product_id").val();
    var month = $("#month").val();
    var price = "";
    var lastmoney = "";
    var discountMoney = "";
    if (product_id == 2) {
        price = 99.9;
    } else if (product_id == 3) {
        price = 299.9;
    } else {
        price = 599.9;
    }
    if (month == 1) {
        lastmoney = price;
    } else if (month == 3) {
        lastmoney = (price*month*0.85).toFixed(2);
    } else {
        lastmoney = (price*month*0.55).toFixed(2);
    }
    discountMoney = (price*month-lastmoney).toFixed(2);
    $("#last_money").text(lastmoney);
    $("#update_date").hide();
    if (discountMoney > 0) {
        $("#discount_money_row").show();
        $("#discountMoney").text(discountMoney);
    } else {
        $("#discount_money_row").hide();
    }
}

function paymentChange(payment_id){
    $("#payment_id").val(payment_id);
    $("#payment_lists li").removeClass("active");
    $("#payment_"+payment_id).addClass("active");
    if(payment_id == 1){
        $("#alipay").hide();
        $("#wechatpay").show();
    } else {
        $("#alipay").show();
        $("#wechatpay").hide();
    }
}

function ordersUpdate(orders_id) {
    var old_product_id = $("#old_product_id").val();
    if (orders_id == 1) {
        $("#products_renew").show();
        $("#products_upgrade").hide();
        $("#type").val(2);
        $("#product_id").val(old_product_id);
        getLastPaidMoney();
    } else {
        $("#products_renew").hide();
        $("#products_upgrade").show();
        $("#type").val(3);

        $("#upgrade_product_lists li").removeClass("active");
        var product_name = "";
        if (old_product_id == 2) {
            product_name = "基础版";
        } else if (old_product_id == 3) {
            product_name = "高级版";
        } else {
            product_name = "旗舰版";
        }
        $("#upgrade_product_id"+old_product_id+" span").text(product_name+"(当前版本)");
        if (old_product_id >= 4) {
            $("#upgrade_product_id"+old_product_id).addClass("active");
        } else {
            product_id = parseInt(old_product_id) + 1;
            $("#product_id").val(product_id);
            $("#upgrade_product_id"+product_id).addClass("active");
        }
        getUpgradePrice();
    }
    $("#orders_update li").removeClass("active");
    $("#orders_"+orders_id).addClass("active");
}

function upgradeProductChange(product_id) {
    var old_product_id = $("#old_product_id").val();
    if (product_id <= old_product_id) {
        mviewToastr("error","您不能选择比当前版本低的会员类型!");
    } else {
        $("#upgrade_product_lists li").removeClass("active");
        $("#upgrade_product_id"+product_id).addClass("active");
        $("#product_id").val(product_id);
    }
    getUpgradePrice();
}

function getUpgradePrice() {
    var old_product_id = $("#old_product_id").val();
    var product_id = $("#product_id").val();
    var startTime = $("#start_time").val();
    var endTime = $("#end_time").val();
    var timeDiff = endTime - startTime
    var ts = Math.round(new Date().getTime()/1000).toString();
    var timeDiffs = endTime - ts
    var diffmonths = Math.floor(timeDiff / 86400 / 30);
    var diffdays = Math.floor(timeDiffs / 86400);
    if (old_product_id == 2) {
        if (diffmonths <= 1) {
            if (product_id == 3) {
                var price = (((299.9-99.9)/30) * diffdays).toFixed(2);
            } else {
                var price = (((599.9-99.9)/30) * diffdays).toFixed(2);
            }
        } else if (diffmonths == 3 || diffmonths == 2) {
            if (product_id == 3) {
                var price = (((765.75-254.75)/90) * diffdays).toFixed(2);
            } else {
                var price = (((1529.74-254.75)/90) * diffdays).toFixed(2);
            }
        } else {
            if (product_id == 3) {
                var price = (((1979.34-659.34)/365) * diffdays).toFixed(2);
            } else {
                var price = (((3959.34-659.34)/365) * diffdays).toFixed(2);
            }
        }
    } else if (old_product_id == 3) {
        if (diffmonths == 1) {
            var price = (((599.9-299.9)/30) * diffdays).toFixed(2);
        } else if (diffmonths == 3) {
            var price = (((1529.74-765.75)/90) * diffdays).toFixed(2);
        } else {
            var price = (((3959.34-1979.34)/365) * diffdays).toFixed(2);
        }
    } else {
        var price = 0.00;
    }
    $("#discount_money_row").hide();
    $("#update_date").text("升级天数"+diffdays+"天").show();
    $("#last_money").text(price);
}

function wechatPay() {
    var userAgent = navigator.userAgent;
    var isMini = /miniProgram/i.test(userAgent);
    if(isMini){
        mviewToastr("error",'小程序不支持付费，请前往天天外链公众号或PC官网操作！');
        return;
    }
    var product_id = $("#product_id").val();
    var month = $("#month").val();
    var payment_id = $("#payment_id").val();
    var type = $("#type").val();
    var wechat = isWeChat() && !isPCWeChat() ? 1 : 2;
    $.ajax({
        url: '/admin/prices/products_lists_pay',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        type: 'POST',
        dataType: 'json',
        data: {
            "product_id":product_id,
            "month":month,
            "payment_id":payment_id,
            "type":type,
            "wechat":wechat,
        },
        success:function (result) {
            if (result.status == "success") {
                if (wechat == 1 && !isPCWeChat()) {
                    WeixinJSBridge.invoke('getBrandWCPayRequest',result.data,(res)=>{
                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                            mviewToastr("success","支持成功,即将跳转订单列表！");
                            setTimeout(function(){
                                window.location.href = "/admin/links_lists/member_orders";
                            },1500);
                        }
                    });
                } else {
                    $("#qrcode").html("");
                    $("#out_trade_no").val(result.data.out_trade_no);
                    $(".wechat-pay-cotain-notice h3 font").text(result.data.price);
                    $(".wechat-pay-cotain-notice h5 font").text(result.data.month);
                    var qrcode = new QRCode(document.getElementById("qrcode"), {
                        text: result.data.code_url,
                        width: 120,
                        height: 120,
                        colorDark : "#000000",
                        colorLight : "#ffffff",
                        correctLevel : QRCode.CorrectLevel.H
                    });
                    $(".wechat-pay-cotain").show();
                    $("#qrcode").show();
                    checkPay();
                }
            } else {
                mviewToastr("error",result.msg);
            }
        },
        error:function (err){
            mviewToastr("error","网络异常,请联系客服处理！");
        }
    });
}

function isWeChat() {
    var ua = navigator.userAgent.toLowerCase();
    return ua.indexOf("micromessenger") !== -1;
}

function isPCWeChat(){
    var ua = navigator.userAgent.toLowerCase();
    return ua.indexOf("macwechat") !== -1 || ua.indexOf("windowswechat") !== -1;
}

function checkPay() {
    var refreshtimes = 1;
    refresh = setInterval(function(){
        refreshtimes += 1;
        checkWechatPay();
        // 5分钟后过期
        if (refreshtimes >= 24) {
            $(".wechat-pay-cotain").hide();
            clearInterval(refresh);
        }
    },5000);
}

function checkWechatPay() {
    var out_trade_no = $("#out_trade_no").val();
    $.ajax({
        url: '/admin/prices/products_wechat_status',
        type: 'GET',
        dataType: 'json',
        data: {
            "out_trade_no":out_trade_no,
        },
        success:function (result) {
            if (result.status == "success") {
                window.location.href = "/admin/links_lists/member_orders";
            }
        },
        error:function (err){
            mviewToastr("error","网络异常,请联系客服处理！");
        }
    });
}

